﻿//////////////////////////////////////////////////////////////////
//
// ScriptFile.cs
//
// Copyright (c) 2012 Dan Pike.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using BLToolkit.Reflection;
using BLToolkit.Reflection.Emit;
using Irony.Parsing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Interfaces;
using Utilities;
using System.IO;
using Irony.Interpreter.Ast;

namespace ScriptIrony
{
   /// <summary>
   /// An implementation based on Irony
   /// </summary>
   public class ScriptFile : IScriptFile
   {
      private static Logger logger_;
      private string displayName_;
      private string filename_;
      private string runnerTypeName_;
      private Type runnerType_;

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// 
      /// </summary>
      public ScriptFile()
      {
         logger_ = Program.logger;
      }
      
      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public string displayName
      {
         get { return displayName_; }
         set { displayName_ = value; }
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public string filename
      {
         get { return filename_; }
         set { filename_ = value; }
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool compile(string filename)
      {
         try
         {
            // Store the type of the owner of this script
            // for example, this may be IPlanet if the script is to customise
            // planet behaviour
            runnerTypeName_ = string.Concat("ScriptIrony.Runner.",
               Path.GetFileNameWithoutExtension(filename));

            logger_.debugFormat("parsing script file '{0}'", filename);
            filename_ = filename;
            string allText = File.ReadAllText(filename_);

            // Parse the script
            Gramp gramp = new Gramp();
            LanguageData language = new LanguageData(gramp);
            Parser parser = new Parser(language);
            ParseTree tree = parser.Parse(allText, filename);
            ParseTreeNode root = tree.Root;
            if (null == root)
            {
               logger_.errorFormat("failed to parse script file '{0}'", filename_);
               return false;
            }

            //AstNode astRoot = root.AstNode as AstNode;

            // Simplify the parse tree
            GrampAst ast = new GrampAst(root);
            //ast.cleanTree(tree);

            // Generate the IL
            AssemblyBuilderHelper assembler = new AssemblyBuilderHelper(Path.ChangeExtension(filename_, "compiled.dll"));
            TypeBuilderHelper typer = assembler.DefineType(runnerTypeName_, typeof(RunnerBase));

            // Global code goes into the constructor, so we start with that
            EmitHelper ctor = typer.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard,
               new Type[] { typeof(IAlmanac) }).Emitter;

            // Do nothing!
            ctor
               .nop
               .ret()
               ;

            // Construct the assembly
            runnerType_ = typer.Create();
            assembler.Save();
            return true;
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public object initialize(object entity)
      {
         try
         {
            
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return null;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool run(object runner, string methodName, object[] parameters)
      {
         try
         {
            
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }
   }
}
